package com.ltxtiyu.video.utils;

import com.alibaba.fastjson.JSONObject;
import com.ltxtiyu.video.common.HttpClientTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.*;


/**
 * 请求微信签名工具类
 *
 * @author lihongtao
 *
 */
public class SignatureUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(SignatureUtil.class);
    /**
     * 微信服务器配置验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
        String[] arr = new String[] { token, timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (Exception e) {
            LOGGER.error("验证微信服务器配置验证签名异常", e);
        }

        content = null;
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * 设置微信上传图片等的请求签名
     *
     * @param request
     *            传入当前请求的request对象
     *
     * @return 返回 signature、nonceStr、timestamp
     */
    public static Map<String, Object> requestUrlSignature(HttpServletRequest request, String accessToken) {
        String url = request.getRequestURL().toString();
        String queryString = request.getQueryString();
        if (StringUtils.isNotBlank(queryString)) {
            url += "?" + queryString;
        }
        String ticket = getTicket(accessToken);
        long timestamp = new Date().getTime();
        Random random = new Random();
        int x = random.nextInt(89999);
        x = x + 10000;

        String nonceStr = "w" + x + "";
        String signature = getSignature(ticket, String.valueOf(timestamp), nonceStr, url);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("signature", signature);
        resultMap.put("nonceStr", nonceStr);
        resultMap.put("timestamp", timestamp);
        return resultMap;
    }

    private static String getSignature(String jsapi_ticket, String timestamp, String nonce, String jsurl) {
        String[] paramArr = new String[] { "jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "noncestr=" + nonce, "url=" + jsurl };
        Arrays.sort(paramArr);
        // 将排序后的结果拼接成一个字符串
        String content = paramArr[0].concat("&" + paramArr[1]).concat("&" + paramArr[2]).concat("&" + paramArr[3]);
        String gensignature = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 对拼接后的字符串进行 sha1 加密
            byte[] digest = md.digest(content.toString().getBytes());
            gensignature = byteToStr(digest);
        } catch (Exception e) {
            LOGGER.error("微信服务器签名异常", e);
        }
        // 将 sha1 加密后的字符串与 signature 进行对比
        if (gensignature != null) {
            return gensignature.toLowerCase();// 返回signature
        } else {
            return "";
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

    private static String getTicket(String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        String ticketUrl = url.replace("ACCESS_TOKEN", accessToken);
        JSONObject resultJson = HttpClientTool.httpRequest(ticketUrl, "GET", null);
        if (resultJson.getString("errcode").equals("42001")||resultJson.getString("errcode").equals("40001")) {
            return "error";
        }
        return resultJson.getString("ticket");
    }
}
